#include "JKCommunicationInterProcess.h"
#include <QDebug>


JKCommunicationInterProcess::JKCommunicationInterProcess(QObject *parent) : QObject(parent)
{
    qRegisterMetaType<QStringList *>();
    mServer = new QLocalServer(this);
    connect(mServer, &QLocalServer::newConnection, this, &JKCommunicationInterProcess::processConnection);
}

JKCommunicationInterProcess::~JKCommunicationInterProcess()
{

}

void JKCommunicationInterProcess::startListen()
{
    if (!mServer->listen("JackysWindowsService")) {
        qDebug() << QStringLiteral("开启LocalServer失败。") << mServer->errorString();
    }
    else {
        qDebug() << QStringLiteral("开启LocalServer成功。");
    }
}

void JKCommunicationInterProcess::stopListen()
{
    mServer->close();
}

void JKCommunicationInterProcess::publish(QString topic)
{
    foreach(QLocalSocket *socket, mConnections) {
        QVariant vTopics = socket->property("topics");
        QStringList *topics = vTopics.value<QStringList *>();
        if (topics->contains(topic)) {
            socket->write(topic.toUtf8());
        }
    }
}

void JKCommunicationInterProcess::processConnection()
{
    if (mServer->hasPendingConnections()) {
        QLocalSocket *pSocket = mServer->nextPendingConnection();
        mConnections.append(pSocket);
        connect(pSocket, &QLocalSocket::disconnected, this, [=](){
            QLocalSocket *socket = qobject_cast<QLocalSocket *>(sender());
            qDebug() << QStringLiteral("客户端断开连接. Client: 0x%1").arg(QString::number((long)socket, 16));
            mConnections.removeOne(socket);
            QVariant vTopics = socket->property("topics");
            QStringList *topics = vTopics.value<QStringList *>();
            qDebug() << QStringLiteral("释放主题列表内存. 地址:0x%1").arg(QString::number(long(topics), 16));
            delete  topics;
        });
        QStringList *pTopics = new QStringList();
        qDebug() << QStringLiteral("创建主题列表. 内存地址:0x%1").arg(QString::number(long(pTopics), 16));
        pSocket->setProperty("topics", QVariant::fromValue(pTopics));
        connect(pSocket, &QLocalSocket::readyRead, this, [=](){
            QLocalSocket *socket = qobject_cast<QLocalSocket *>(sender());
            QVariant vTopics = socket->property("topics");
            QStringList *topics = vTopics.value<QStringList *>();
            QByteArray baContent = socket->readAll();
            QList<QByteArray> baTopics = baContent.split('\n');
            foreach(QByteArray topic, baTopics) {
                if (topic != "" && topics->indexOf(topic) == -1) {
                    topics->append(topic);
                    qDebug() << QStringLiteral("添加订阅主题. Client: 0x%1，主题：%2").arg(QString::number((long)pSocket, 16)).arg(QString(topic));
                }
            }
        });

        qDebug() << QStringLiteral("有客户端接入. Client: 0x%1").arg(QString::number((long)pSocket, 16));
    }
}
